package com.upf1sh.controller;

import com.baomidou.mybatisplus.extension.api.R;
import com.upf1sh.bean.FileEntity;
import com.upf1sh.common.FileUploadUtils;
import com.upf1sh.common.upf1sh;
import com.upf1sh.config.ServerConfig;
import com.upf1sh.mapper.FileMapper;
import com.upf1sh.service.FileService;
import com.upf1sh.utils.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 公共开放接口
 * @Title: publicController
 * @Package com.upf1sh.controller
 * @Author: ZhaoXu
 * @CreateTime: 2024/12/2 14:27
 */

@RequestMapping("/public")
@RestController
public class publicController {
    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private FileMapper fileMapper;

    @PostMapping("/upload")
    public R upload(MultipartFile file) throws Exception {
        try {
            // 上传文件路径
            String filePath = upf1sh.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            Map<String, Object> map = new HashMap<>();
            map.put("url", url);
            map.put("fileName", fileName);
            map.put("newFileName", FileUtils.getName(fileName));
            map.put("originalFilename", file.getOriginalFilename());
            FileEntity fileEntity = new FileEntity();
            String fileExtension = fileName.substring( fileName.lastIndexOf('.') + 1);
            fileEntity.setName(file.getOriginalFilename());
            fileEntity.setBelong("公共");
            fileEntity.setSize(1233);
            fileEntity.setType(fileExtension);
            fileEntity.setDate(LocalDateTime.now());
            fileEntity.setPath(url);
            fileMapper.insert(fileEntity);
            return R.ok(map);
        }  catch (Exception e){
            return R.failed(e.getMessage());
        }
    }

}
